/**
 * Geppetto WebSocket React Hook
 */

import { useState, useEffect, useCallback } from 'react';
import { geppettoWS, GeppettoMessage } from '../services/GeppettoWebSocketService';

export interface NetworkData {
  cells: Array<{
    gid: number;
    tags: any;
    x: number;
    y: number;
    z: number;
    pop: string;
    cellType: string;
  }>;
  connections: Array<{
    preGid: number;
    postGid: number;
    weight: number;
    delay: number;
    synMech: string;
  }>;
  populations: Array<{
    name: string;
    cellType: string;
    numCells: number;
  }>;
}

export interface SimulationData {
  spikes: Array<{
    t: number;
    gid: number;
  }>;
  traces: Record<string, any>;
  lfp: any[];
}

export interface UseGeppettoWebSocketReturn {
  // 连接状态
  isConnected: boolean;
  isConnecting: boolean;
  error: string | null;

  // 数据
  networkData: NetworkData | null;
  simulationData: SimulationData | null;
  isSimulationRunning: boolean;

  // 方法
  connect: () => Promise<void>;
  disconnect: () => void;
  initModel: () => Promise<void>;
  getNetwork: () => Promise<void>;
  runSimulation: () => Promise<void>;
  getSimulationData: () => Promise<void>;
  executeCode: (code: string) => Promise<string>;
}

export function useGeppettoWebSocket(): UseGeppettoWebSocketReturn {
  const [isConnected, setIsConnected] = useState(false);
  const [isConnecting, setIsConnecting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [networkData, setNetworkData] = useState<NetworkData | null>(null);
  const [simulationData, setSimulationData] = useState<SimulationData | null>(null);
  const [isSimulationRunning, setIsSimulationRunning] = useState(false);

  // 连接到 WebSocket
  const connect = useCallback(async () => {
    try {
      setIsConnecting(true);
      setError(null);
      await geppettoWS.connect();
      setIsConnected(true);
      setIsConnecting(false);
    } catch (err) {
      setError(err instanceof Error ? err.message : '连接失败');
      setIsConnecting(false);
      setIsConnected(false);
    }
  }, []);

  // 断开连接
  const disconnect = useCallback(() => {
    geppettoWS.disconnect();
    setIsConnected(false);
  }, []);

  // 初始化模型
  const initModel = useCallback(async () => {
    try {
      setError(null);
      await geppettoWS.initModel();
      console.log('✅ 模型初始化成功');
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : '初始化模型失败';
      setError(errorMsg);
      throw err;
    }
  }, []);

  // 获取网络数据
  const getNetwork = useCallback(async () => {
    try {
      setError(null);
      const response = await geppettoWS.getNetwork();
      if (response.data) {
        setNetworkData(response.data);
        console.log('✅ 网络数据获取成功:', response.data);
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : '获取网络数据失败';
      setError(errorMsg);
      throw err;
    }
  }, []);

  // 运行仿真
  const runSimulation = useCallback(async () => {
    try {
      setError(null);
      setIsSimulationRunning(true);
      await geppettoWS.runSimulation();
      setIsSimulationRunning(false);
      console.log('✅ 仿真运行完成');
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : '运行仿真失败';
      setError(errorMsg);
      setIsSimulationRunning(false);
      throw err;
    }
  }, []);

  // 获取仿真数据
  const getSimulationData = useCallback(async () => {
    try {
      setError(null);
      const response = await geppettoWS.getSimulationData();
      if (response.data) {
        setSimulationData(response.data);
        console.log('✅ 仿真数据获取成功:', response.data);
      }
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : '获取仿真数据失败';
      setError(errorMsg);
      throw err;
    }
  }, []);

  // 执行代码
  const executeCode = useCallback(async (code: string): Promise<string> => {
    try {
      setError(null);
      const response = await geppettoWS.executeCode(code);
      console.log('✅ 代码执行成功:', response.result);
      return response.result || '';
    } catch (err) {
      const errorMsg = err instanceof Error ? err.message : '执行代码失败';
      setError(errorMsg);
      throw err;
    }
  }, []);

  // 监听消息
  useEffect(() => {
    // 连接状态消息
    const handleConnection = (message: GeppettoMessage) => {
      console.log('连接消息:', message);
      setIsConnected(true);
    };

    // 仿真开始消息
    const handleSimulationStarted = (message: GeppettoMessage) => {
      console.log('仿真开始:', message);
      setIsSimulationRunning(true);
    };

    // 仿真完成消息
    const handleSimulationCompleted = (message: GeppettoMessage) => {
      console.log('仿真完成:', message);
      setIsSimulationRunning(false);
    };

    // 错误消息
    const handleError = (message: GeppettoMessage) => {
      console.error('错误消息:', message);
      setError(message.error || '未知错误');
    };

    // 注册处理器
    geppettoWS.on('connection', handleConnection);
    geppettoWS.on('simulation_started', handleSimulationStarted);
    geppettoWS.on('simulation_completed', handleSimulationCompleted);
    geppettoWS.on('error', handleError);

    // 清理
    return () => {
      geppettoWS.off('connection', handleConnection);
      geppettoWS.off('simulation_started', handleSimulationStarted);
      geppettoWS.off('simulation_completed', handleSimulationCompleted);
      geppettoWS.off('error', handleError);
    };
  }, []);

  return {
    isConnected,
    isConnecting,
    error,
    networkData,
    simulationData,
    isSimulationRunning,
    connect,
    disconnect,
    initModel,
    getNetwork,
    runSimulation,
    getSimulationData,
    executeCode,
  };
}

